<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="计划名称" prop="planId">
        <el-select
          v-model="queryParams.planId"
          placeholder="请选择评价计划"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="plan in planList"
            :key="plan.id"
            :label="plan.planName"
            :value="plan.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="科目名称" prop="subjectName">
        <el-input
          v-model="queryParams.subjectName"
          placeholder="请输入科目名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="科目代码" prop="subjectCode">
        <el-input
          v-model="queryParams.subjectCode"
          placeholder="请输入科目代码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="科目类型" prop="subjectType">
        <el-select
          v-model="queryParams.subjectType"
          placeholder="请选择科目类型"
          clearable
          class="!w-240px"
        >
          <el-option label="理论知识" value="theory" />
          <el-option label="技能操作" value="practical" />
          <el-option label="综合评价" value="comprehensive" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="openBatchCreate"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 批量新增
        </el-button>
        <el-button
          type="info"
          plain
          @click="openTemplateCreate"
        >
          <Icon icon="ep:document-add" class="mr-5px" /> 模板创建
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="科目名称" align="center" prop="subjectName" width="150" />
      <el-table-column label="科目代码" align="center" prop="subjectCode" width="120" />
      <el-table-column label="所属计划" align="center" prop="planName" width="200" />
      <el-table-column label="科目类型" align="center" prop="subjectType" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.EVAL_SUBJECT_TYPE" :value="scope.row.subjectType" />
        </template>
      </el-table-column>
      <el-table-column label="权重" align="center" prop="subjectWeight" width="80">
        <template #default="scope">
          <span v-if="scope.row.subjectWeight != null && !isNaN(scope.row.subjectWeight)">
            {{ (scope.row.subjectWeight * 100).toFixed(1) }}%
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="合格分数" align="center" prop="passingScore" width="80" />
      <el-table-column label="满分" align="center" prop="maxScore" width="80" />
      <el-table-column label="考试时长" align="center" prop="examDuration" width="100">
        <template #default="scope">
          <span v-if="scope.row.examDuration">
            {{ scope.row.examDuration }}分钟
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="考试地点" align="center" prop="examLocation" width="120">
        <template #default="scope">
          <span v-if="scope.row.examLocation">{{ scope.row.examLocation }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="科目描述" align="center" prop="subjectDescription" width="150">
        <template #default="scope">
          <span v-if="scope.row.subjectDescription" :title="scope.row.subjectDescription">
            {{ scope.row.subjectDescription.length > 20 ? scope.row.subjectDescription.substring(0, 20) + '...' : scope.row.subjectDescription }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="creator" width="100">
        <template #default="scope">
          <span v-if="scope.row.creator">{{ scope.row.creator }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleCopy(scope.row)"
          >
            复制
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <SubjectForm ref="formRef" @success="getList" />
  
  <!-- 批量创建弹窗 -->
  <SubjectBatchCreate ref="batchCreateRef" @success="getList" />
  
  <!-- 模板创建弹窗 -->
  <SubjectTemplateCreate ref="templateCreateRef" @success="getList" />
  
  <!-- 复制弹窗 -->
  <SubjectCopy ref="copyRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { DICT_TYPE } from '@/utils/dict'
import { EvalSubjectVO, EvalSubjectPageReqVO, getSubjectPage, deleteSubject, exportSubject } from '@/api/eval/subject'
import { EvalPlanVO, getPlanListByStatus, getPlanPage } from '@/api/eval/plan'
import SubjectForm from './SubjectForm.vue'
import SubjectBatchCreate from './SubjectBatchCreate.vue'
import SubjectTemplateCreate from './SubjectTemplateCreate.vue'
import SubjectCopy from './SubjectCopy.vue'

/** 评价科目 列表 */
defineOptions({ name: 'EvalSubject' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EvalSubjectVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive<EvalSubjectPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  planId: undefined,
  subjectName: undefined,
  subjectCode: undefined,
  subjectType: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const planList = ref<EvalPlanVO[]>([]) // 计划列表

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getSubjectPage(queryParams)

    // 为每个科目添加计划名称
    list.value = data.list.map(item => {
      const plan = planList.value.find(p => p.id === item.planId)
      return {
        ...item,
        planName: plan?.planName || '未知计划'
      }
    })
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 批量创建操作 */
const batchCreateRef = ref()
const openBatchCreate = () => {
  batchCreateRef.value.open()
}

/** 模板创建操作 */
const templateCreateRef = ref()
const openTemplateCreate = () => {
  templateCreateRef.value.open()
}

/** 复制操作 */
const copyRef = ref()
const handleCopy = (row: EvalSubjectVO) => {
  copyRef.value.open([row.id])
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteSubject(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await exportSubject(queryParams)
    download.excel(data, '评价科目.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 加载计划列表 */
const loadPlanList = async () => {
  try {
    // 获取所有状态的计划以便正确显示科目关联的计划名称
    const allPlans = await Promise.all([
      getPlanListByStatus(0), // 草稿
      getPlanListByStatus(1), // 已提交
      getPlanListByStatus(2), // 已审批
      getPlanListByStatus(3), // 已发布
      getPlanListByStatus(4), // 进行中
      getPlanListByStatus(5)  // 已完成
    ])
    planList.value = allPlans.flat()
  } catch (error) {
    console.error('加载计划列表失败:', error)
    planList.value = []
  }
}

/** 初始化 **/
onMounted(async () => {
  await loadPlanList()
  getList()
})
</script>
